package org.example.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author xietl
 * @date 2025/8/30  16:52
 * @description 异步处理配置类，支持Redis状态的异步更新
 */
@Slf4j
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
    @Bean(name="asyncExecutor")
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);  // 核心线程数
        executor.setMaxPoolSize(8);    // 最大线程数
        executor.setQueueCapacity(200);  // 队列容量（有界队列，防止溢出）
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //// 队列满时，由提交任务的线程执行（避免任务丢失）
        executor.setKeepAliveSeconds(60);    // 线程空闲时间，超过此时间线程会被销毁
        executor.setThreadNamePrefix("redis-async-");
        executor.initialize();
        return executor;
    }
    /**
     * 异步处理异常捕获
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return ((ex, method, params) -> {
            log.info("AsyncUncaughtExceptionHandler method {}, params: {}", method, params);
        });
    }
}
